import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "../views/HomeView.vue";
import { isLogined } from "../utils/auth";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Home",
    component: HomeView,
  },
  {
    path: "/about",
    name: "about",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
  },

  {
    name: "User",
    path: "/user",
    component: () => import("../views/User.vue"),
    meta: {
      needLogin: true,
    },
  },
  {
    name: "Cart",
    path: "/cart",
    component: () => import("../views/Cart.vue"),
    meta: {
      needLogin: true,
      hideTabBar: true,
    },
  },
  {
    name: "List",
    path: "/list",
    component: () => import("../views/List.vue"),
  },
  {
    name: "Detail",
    path: "/detail/:id",
    component: () => import("../views/Detail.vue"),
    meta: {
      hideTabBar: true,
    },
  },
  {
    name: "Reg",
    path: "/reg",
    component: () => import("../views/Reg.vue"),
    meta: {
      hideTabBar: true,
    },
  },
  {
    name: "Login",
    path: "/login",
    component: () => import("../views/Login.vue"),
    meta: {
      hideTabBar: true,
    },
  },
];
const router = new VueRouter({
  routes,
  mode: "hash",
});

router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    if (isLogined()) {
      next();
    } else {
      next({
        name: "Login",
      });
    }
  } else {
    next();
  }
});

//解决跳转报错
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};

export default router;
